using UnityEngine;
using System.Collections;

public class GravitationManager : MonoBehaviour {

    public float        _graviationRadius = 4.0f;
    public float        _collidersize = 1.4f;

    private GameObject[] _players;

	// Use this for initialization
	void Start () {
        SphereCollider _sc = gameObject.AddComponent<SphereCollider>();
        _sc.radius = _collidersize;
        _sc.isTrigger = true;
	}

    void Awake()
    {
        _players = GameObject.FindGameObjectsWithTag( "Player" );
    }
	// Update is called once per frame
	void Update () {
        foreach (GameObject _player in _players)
        {
            RaycastHit raycastHit;
            Vector3 planetCoreToObj = (_player.transform.position - transform.position).normalized;
            Physics.Raycast(transform.position, planetCoreToObj, out raycastHit, 50.0f);
            Vector3 planetSurfaceToObj = ( raycastHit.point - _player.transform.position).normalized;

            if (Physics.Raycast(raycastHit.point, planetSurfaceToObj, _graviationRadius))
                ((Character)_player.GetComponent(typeof(Character)))._currentPlanet = this.transform;

        } 
	}

    void OnTriggerEnter(Collider other)
    {
        Character _char = other.gameObject.GetComponent<Character>();
        //set current planet of character depending on highest mass
        if (_char != null && ( _char._currentPlanet == null || _char._currentPlanet.rigidbody.mass <= gameObject.rigidbody.mass ) )
        {
            _char._currentPlanet = gameObject.transform;
            Debug.Log("changed planet");
        }
    }

    void OnCollisionExit(Collision collisionInfo)
    {
        Character _char = collisionInfo.gameObject.GetComponent<Character>();
        //set current planet of character depending on highest mass
       // if (_char != null)
         //   _char._currentPlanet = null;
    }
}
